#!/bin/bash

# Copyright (c) 2023 boomlee.com
# Author: boomlee.com

###
#用于管理集群的节点，便捷执行远程命令
#myscp -iprange=10.0.1.0~10.0.1.10 -localdir=/tmp -remotedir=/tmp
#myscp -ipconf=config/vm_info -localdir=/tmp -remotedir=/tmp
###

##控制日志颜色
CSTART_CYAN='\033[36m' #蓝色
CSTART_YELLOW='\033[33m' #黄色
CEND='\033[0m'

##入参
PARAMS="$*"
PARAMS_LEN="$#"

function main() {
    #ip配置
    local ipconf=$(echo "$PARAMS" | sed -n 's/.*-ipconf=\(.*\)/\1/p' | awk -F' ' '{print $1}')
    #ip区间
    local start_ip=$(echo "$PARAMS" | sed -n 's/.*-iprange=\([0-9.]*\)~[0-9.]*.*/\1/p')
    local end_ip=$(echo "$PARAMS" | sed -n 's/.*-iprange=[0-9.]*~\([0-9.]*\).*/\1/p')
    #scp 目录: 默认本地->远端
    local localdir=$(echo "${PARAMS}" | sed -n 's/.*-localdir=\(.*\)/\1/p' | awk -F' ' '{print $1}')
    local remotedir=$(echo "${PARAMS}" | sed -n 's/.*-remotedir=\(.*\)/\1/p' | awk -F' ' '{print $1}')

    #针对入参调用不同的方法
    if [[ -z $start_ip ]] || [[ -z $end_ip ]];
    then
        loop_ip_by_conf "$ipconf" "$localdir" "$remotedir"
    else
        loop_ip_by_range "$start_ip" "$end_ip" "$localdir" "$remotedir"
    fi
}

#循环ip，批量处理
function loop_ip_by_conf() {
    local ipconf="$1"
    local localdir="$2"
    local remotedir="$3"
    
    cat "${ipconf:-config/vm_info}" | grep -v "^#" | grep -v "^$" | while read ipaddr name passwd
    do
        # 执行命令（忽略报错）
        run_scp "$ipaddr" "$localdir" "$remotedir" || true
    done
}

#循环ip，批量处理
function loop_ip_by_range() {
    local start_ip="$1"
    local end_ip="$2"
    local localdir="$3"
    local remotedir="$4"

    # 循环遍历IP地址范围
    local start_int=$(ip_to_int "$start_ip")
    local end_int=$(ip_to_int "$end_ip")
    for ((i = start_int; i <= end_int; i++)); do
        # 将整数转换为IP地址
        local ipaddr="$(( (i & 0xFF000000) >> 24 )).$(( (i & 0x00FF0000) >> 16 )).$(( (i & 0x0000FF00) >> 8 )).$((i & 0x000000FF))"
        # 执行命令（忽略报错）
        run_scp "$ipaddr" "$localdir" "$remotedir" || true
    done
}

#执行命令
function run_scp() {
    local ipaddr="$1"
    local localdir="$2"
    local remotedir="$3"

    local system_version=$(ssh -n $ipaddr "cat /etc/redhat-release | sed 's/ //g'")
    echo -e "${CSTART_CYAN}>>>>$ipaddr>$system_version$CEND"

    #跳过自己
    local me=$(hostname -I)
    if [[ $me == *$ipaddr* ]]; then
        echo -e "${CSTART_YELLOW}$me - $ipaddr [break]$CEND"
    else
        echo -e "${CSTART_YELLOW}$me -> $ipaddr$CEND"
        scp -r $localdir $ipaddr:$remotedir
    fi
}

# 将IP地址转换为整数
function ip_to_int() {
    local ip="$1"
    local a b c d
    IFS=. read -r a b c d <<< "$ip"
    echo "$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"
}

main
